import * as base from "./base.js";
import instance from './request.js';
import { $, $$ } from './base.js';




window.addEventListener('load', function () {

    //图片
    let picturesarr = [];
    //设置入住人数
    let renshunum = 1;
    //新建房源id
    let homeid = 0;


    //返回到主页面
    $('.nav-r-2').addEventListener('click', function () {
        location.href = 'index.html';
    })


    // 获取视频元素
    const video = $('.first_r video');

    // 静音自动播放
    video.muted = true;
    window.addEventListener('load', function () {
        // 静音自动播放
        video.muted = true;
        video.play()
            .then(function () {
                // 静音播放成功，取消静音
                video.muted = false;
            })
            .catch(function (error) {
                // 静音播放失败，提示用户点击页面触发播放
                video.muted = false;
                video.addEventListener('click', function () {
                    video.play();
                });
            });
    });


    let pubnum = 1;
    let fannum = 0;
    $('.publish_bbox_r').addEventListener('click', function () {
        if (pubnum == 9) {
            if ($('.add_remarkbox_text textarea').value && $('.fangyuandeltail textarea').value && $('.pricebox input').value && picturesarr.length) {
                base.debounce(instance.post('/home', {
                    title: base.SaferHTML`${$('.add_remarkbox_text textarea').value}`,
                    introduce: base.SaferHTML`${$('.fangyuandeltail textarea').value}`,
                    price: base.SaferHTML`${$('.pricebox input').value}`,
                    pictures: picturesarr,
                    tenant: renshunum,
                    houseTypeId: $('.pub_current').getAttribute('id')
                }, {
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                }).then(response => {
                    console.log(response.data.data.homeId);
                    let addarr = response.data.data;

                    homeid = response.data.data.homeId;
                    fannum = 0;
                    base.tooltipBox('', '房源创建成功', '1');

                }).catch(error => {
                    console.error(error)
                }))
                
            } else {
                base.tooltipBox('', '还未完善房源信息', '0');
                fannum = 1;
            }

        }

        if (pubnum == 10) {
            base.tooltipBox('', '已完成所有创建房源步骤!', '1');
            setTimeout(function () {
                location.href = 'index.html';
            }, 500);
        }
        if (fannum == 1) {
            return;
        }


        $(`.publish${pubnum}`).style.display = 'none';
        if (pubnum == 3 || pubnum == 7) {
            $(`.publish${pubnum + 1}`).style.display = 'flex';

            if (pubnum == 3) $('.second_r video').play();
            if (pubnum == 7) $('.third_r video').play();
        } else {
            $(`.publish${pubnum + 1}`).style.display = 'block';
        }


        if (pubnum == 8) {
            $('.publish_bbox_r').innerHTML = '完成';
        }


        pubnum++;
        console.log(pubnum);
        let pubarr = $$('.progress_bar_l_box');

        switch (pubnum) {
            case 2:
                pubarr[1].classList.add('slide-in');
                pubarr[1].classList.remove('slide-out');
                break;
            case 3:
                pubarr[2].classList.add('slide-in');
                pubarr[2].classList.remove('slide-out');
                break;
            case 4:
                pubarr[3].classList.add('slide-in');
                pubarr[3].classList.remove('slide-out');
                break;
            case 5:
                pubarr[4].classList.add('slide-in');
                pubarr[4].classList.remove('slide-out');
                break;
            case 6:
                pubarr[5].classList.add('slide-in');
                pubarr[5].classList.remove('slide-out');
                break;
            case 7:
                pubarr[6].classList.add('slide-in');
                pubarr[6].classList.remove('slide-out');
                break;
            case 8:
                pubarr[7].classList.add('slide-in');
                pubarr[7].classList.remove('slide-out');
                break;
            case 9:
                pubarr[8].classList.add('slide-in');
                pubarr[8].classList.remove('slide-out');
                break;
            case 10:
                pubarr[9].classList.add('slide-in');
                pubarr[9].classList.remove('slide-out');
                break;
            default:
                // 如果 pubnum 不匹配任何情况，则执行默认操作
                break;
        }

    })


    $('.publish_bbox_l').addEventListener('click', function () {
        if (pubnum == 1 || pubnum == 10) {
            console.log(1);
            return;
        }
        $(`.publish${pubnum}`).style.display = 'none';
        if (pubnum == 2 || pubnum == 5 || pubnum == 9) {
            $(`.publish${pubnum - 1}`).style.display = 'flex';
            if (pubnum == 2) $('.first_r video').play();
            if (pubnum == 5) $('.second_r video').play();
            if (pubnum == 9) $('.third_r video').play();
        } else {
            $(`.publish${pubnum - 1}`).style.display = 'block';
        }

        if (pubnum == 9) {
            $('.publish_bbox_r').innerHTML = '下一步';
        }



        let pubarr = $$('.progress_bar_l_box');
        switch (pubnum) {
            case 2:
                pubarr[1].classList.remove('slide-in');
                pubarr[1].classList.add('slide-out');
                break;
            case 3:
                pubarr[2].classList.remove('slide-in');
                pubarr[2].classList.add('slide-out');
                break;
            case 4:
                pubarr[3].classList.remove('slide-in');
                pubarr[3].classList.add('slide-out');
                break;
            case 5:
                pubarr[4].classList.remove('slide-in');
                pubarr[4].classList.add('slide-out');
                break;
            case 6:
                pubarr[5].classList.remove('slide-in');
                pubarr[5].classList.add('slide-out');
                break;
            case 7:
                pubarr[6].classList.remove('slide-in');
                pubarr[6].classList.add('slide-out');
                break;
            case 8:
                pubarr[7].classList.remove('slide-in');
                pubarr[7].classList.add('slide-out');
                break;
            case 9:
                pubarr[8].classList.remove('slide-in');
                pubarr[8].classList.add('slide-out');
                break;
            case 10:
                pubarr[9].classList.remove('slide-in');
                pubarr[9].classList.add('slide-out');
                break;
            default:
                // 如果 pubnum 不匹配任何情况，则执行默认操作
                break;
        }

        pubnum--;
    })



    // 房源类型标签
    $$('.houseTypeid_bb ul li').forEach(function (value, index, array) {
        $$('.houseTypeid_b ul li')[index].addEventListener('click', function () {
            $$('.houseTypeid_b ul li').forEach(function (value, index1, array) {
                $$('.houseTypeid_b ul li')[index1].classList.remove('pub_current');
            })

            $$('.houseTypeid_b ul li')[index].classList.add('pub_current');
        })
    })




    //添加房源标签
    $('.add_houselabel').addEventListener('click', function () {
        $('.editormask').style.display = 'block';
        $('.change_wish').style.display = 'block';
        $('.change_wish').classList.add('slidedownup');
    })

    //限制字数
    function controlnum(obj, obj1) {
        $(`${obj}`).addEventListener('input', function () {
            const count = this.value.length;
            $(`${obj1} .min_num`).textContent = count;
            if (count > parseInt($(`${obj1} .max_num`).textContent)) {
                $(`${obj1} .min_num`).textContent = count - 1;
            }
            if (count > parseInt($(`${obj1} .max_num`).textContent)) {
                // 如果超过最大字数限制，则截断输入
                this.value = this.value.slice(0, parseInt($(`${obj1} .max_num`).textContent));
            }
        });
    }
    function inputanimate(obj, obj2) {
        $(`${obj} input`).addEventListener('focus', function () {
            $(`${obj2}`).style.transform = 'scale(0.8) translateX(-10px) translateY(-15px)';
            $(`${obj}`).style.border = '1px solid #222';
        })
        $(`${obj} input`).addEventListener('blur', function () {
            $(`${obj}`).style.border = '1px solid #b0b0b0';
            if (!($(`${obj} input`).value)) {
                $(`${obj2}`).style.transform = 'scale(1) translateX(0px) translateY(0px)';
            }
        })
    }


    controlnum('.wishcreate_m_t input', '.wishcreate_m_b');
    inputanimate('.wishcreate_m_t', '.wishcreate_m_name');

    //标题
    controlnum('.add_remarkbox_text textarea', '.add_remarkbox_textm');
    controlnum('.fangyuandeltail textarea', '.fangyuandeltail_m');


    //关闭房源标签
    $('.delete_wish_close').addEventListener('click', function () {
        $('.editormask').style.display = 'none';
        $('.change_wish').style.display = 'none';
    })
    $('.delete_wish_b_l').addEventListener('click', function () {
        $('.delete_wish_close').click();
    })
    $('.editormask').addEventListener('click', function () {
        if ($('.change_wish').style.display == 'block')
            $('.delete_wish_close').click();
        if ($('.delete_wish').style.display == 'block')
            $('.deladdnotebut').click();
    })

    let addanote = 0;
    let addyes = 0;
    $('.delete_wish_b_r').addEventListener('click', base.debounce(function () {
        let addnoteinput = $('.wishcreate_m_t input').value;
        if (addnoteinput) {
            instance.post('/label/add', {
                name: addnoteinput
            }, {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {
                console.log(response.data);
                if (response.data.code == 200) {
                    addyes = 1;
                    addanote = response.data.data.labelId;
                }

            }).then(response => {
                if (addanote && addyes == 1) {
                    addnotefun();
                } else {
                    instance.get(`/label`, {
                        headers: {
                            'Authorization': window.localStorage.getItem('token'),
                            'Content-Type': 'application/json',
                        }
                    }).then(response => {
                        let wisharr = response.data.data;
                        console.log(wisharr);

                        wisharr.forEach(function (value, index, array) {
                            if (wisharr[index].name == addnoteinput) {
                                addanote = wisharr[index].id;
                                addnotefun();
                                return;
                            }
                        })
                    })
                }
            }).catch(error => {
                console.error(error)
            })
        }
    })
    )


    function addnotefun() {
        instance.post(`/home/label/${homeid}`, {
            labelId: addanote
        }, {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            console.log(response.data);
            // let addanote = response.data.data.labelId;

            let str = `<li style="animation-delay: 500ms;" id="${addanote}">
            <div class="delete_wish_close" style="top: 3px;
            left: 165px;">
                <div class="delete_wish_mask"></div>
                <button aria-label="删除「哈哈哈」（未共享）" type="button" class="l1ovpqvx cwgqky9 dir dir-ltr"><span
                        class="i13tpwjr dir dir-ltr"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"
                            aria-hidden="true" role="presentation" focusable="false"
                            style="display: block; height: 12px; width: 12px; fill: currentcolor;">
                            <path
                                d="m14.3.3 1.4 1.4L9.43 8l6.29 6.3-1.42 1.4L8 9.43 1.7 15.7.3 14.29 6.57 8 .3 1.7 1.71.3 8 6.57z">
                            </path>
                        </svg></span></button>
            </div>
            <span class="ellipsis" style="width: 168px;">${$('.wishcreate_m_t input').value}</span>
        </li>`

            $('.add_houselabel').insertAdjacentHTML('beforebegin', str);

            addyes = 0;

            $('.delete_wish_close').click();
            $('.wishcreate_m_t input').value = '';
            $('.wishcreate_m_name').style.transform = 'scale(1) translateX(0px) translateY(0px)';

            base.tooltipBox('', '添加标签成功!', '1');

        }).catch(error => {
            console.error(error)
        })
    }




    //删除标签
    $('.delhouseadd_ul').addEventListener('click', function (event) {
        const targetElement = event.target;

        if (targetElement.classList.contains('delete_wish_mask')) {
            $('.editormask').style.display = 'block';
            $('.delete_wish').style.display = 'block';
            $('.delete_wish').classList.add('visible');

            $('.delete_wish_name').innerHTML = targetElement.parentNode.parentNode.children[1].innerHTML;

            let detailid = targetElement.parentNode.parentNode.getAttribute('id');
            console.log(detailid);

            $('.change_wish_b_r').onclick = base.debounce(function () {
                instance({
                    url: `/home/label/${homeid}`,
                    method: 'DELETE',
                    data: {
                        labelId: detailid
                    },
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                }).then(response => {
                    console.log(response);
                    $('.editormask').style.display = 'none';
                    $('.delete_wish').style.display = 'none';
                    base.tooltipBox('', '删除标签成功!', '1');
                    targetElement.parentNode.parentNode.remove();

                }).catch(error => {
                    console.error(error)
                })
            })


        }
    })

    $('.deladdnotebut').addEventListener('click', function () {
        $('.delete_wish').classList.add('reverse-animation');

        // 等待动画结束后移除.visible和.reverse-animation类名
        setTimeout(function () {
            $('.delete_wish').classList.remove('visible', 'reverse-animation');
            $('.editormask').style.display = 'none';
            $('.delete_wish').style.display = 'none';
        }, 500);
    })
    $('.change_wish_b_l').addEventListener('click', function () {
        $('.deladdnotebut').click();
    })





    //设置入住人数

    function ren_r(index, num) {
        $$('.ren_add')[index].addEventListener('click', function () {
            if (renshunum == 16 - 1) {
                $$('.ren_add')[0].style.border = '1px solid #b2dadb';
                $$('.ren_add svg')[0].style.fill = '#b2dadb';
                $$('.ren_add')[1].style.border = '1px solid #b2dadb';
                $$('.ren_add svg')[1].style.fill = '#b2dadb';
                $$('.ren_tenant')[index].innerHTML++;
                if ($$('.ren_tenant')[index].innerHTML != num) {
                    $$('.ren_reduce')[index].style.border = '1px solid #008489';
                    $$('.ren_reduce svg')[index].style.fill = '#008489';
                }


                renshunum++;
            } else if (renshunum < 16 - 1) {
                $$('.ren_reduce')[index].style.border = '1px solid #008489';
                $$('.ren_reduce svg')[index].style.fill = '#008489';
                $$('.ren_tenant')[index].innerHTML++;

                renshunum++;
            }
            console.log(renshunum);

        })

    }
    ren_r(0, 1);


    function ren_l(index, num) {
        $$('.ren_reduce')[index].addEventListener('click', function () {
            if (renshunum > 1 && ($$('.ren_tenant')[index].innerHTML > num + 1)) {
                $$('.ren_add')[0].style.border = '1px solid #008489';
                $$('.ren_add svg')[0].style.fill = '#008489';
                $$('.ren_add')[1].style.border = '1px solid #008489';
                $$('.ren_add svg')[1].style.fill = '#008489';

                $$('.ren_tenant')[index].innerHTML--;

                renshunum--;
            } else if ($$('.ren_tenant')[index].innerHTML == num + 1) {
                $$('.ren_reduce')[index].style.border = '1px solid #b2dadb';
                $$('.ren_reduce svg')[index].style.fill = '#b2dadb';
                $$('.ren_tenant')[index].innerHTML--;

                renshunum--;
            }
            console.log(renshunum);
        })

    }
    ren_l(0, 1);



    function other_r(num) {
        $$('.ren_add')[num].addEventListener('click', function () {
            if ($$('.ren_tenant')[num].innerHTML == 5 - 1) {
                $$('.ren_add')[num].style.border = '1px solid #b2dadb';
                $$('.ren_add svg')[num].style.fill = '#b2dadb';
                $$('.ren_tenant')[num].innerHTML++;
                return;
            } else if ($$('.ren_tenant')[num].innerHTML < 5 - 1) {
                $$('.ren_reduce')[num].style.border = '1px solid #008489';
                $$('.ren_reduce svg')[num].style.fill = '#008489';
                $$('.ren_tenant')[num].innerHTML++;
            }
        })
    }
    other_r(1);
    other_r(2);
    other_r(3);


    function other_l(num) {
        $$('.ren_reduce')[num].addEventListener('click', function () {
            if ($$('.ren_tenant')[num].innerHTML == 1) {
                $$('.ren_reduce')[num].style.border = '1px solid #b2dadb';
                $$('.ren_reduce svg')[num].style.fill = '#b2dadb';
                $$('.ren_tenant')[num].innerHTML--;
                return;
            } else if ($$('.ren_tenant')[num].innerHTML > 1) {
                $$('.ren_add')[num].style.border = '1px solid #008489';
                $$('.ren_add svg')[num].style.fill = '#008489';
                $$('.ren_tenant')[num].innerHTML--;
            }
        })
    }
    other_l(1);
    other_l(2);
    other_l(3);



    //上传房源图片
    $('.uploadBtn').addEventListener('click', base.debounce(function () {
        const fileInput = document.getElementById('camera');
        const formData = new FormData();

        // 遍历所有选中的文件并添加到 formData
        for (let i = 0; i < fileInput.files.length; i++) {
            formData.append('pictures', fileInput.files[i]);
        }

        instance.post('/picture', formData, {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'multipart/form-data'
            }
        }).then(response => {
            // 处理上传成功后的响应数据
            console.log('上传成功:', response);
            // 更新页面中的图片显示
            response.data.data.forEach(url => {
                picturesarr.push(url);
                let str = `<li>
                <img src="${url}" alt="">
            </li>`

                $('.houseTypeid_m ul').insertAdjacentHTML('beforeend', str);
            });
        }).catch(error => {
            console.error('上传失败:', error);
        });
    }));




})